<?php
$smartThumb = new SmartThumb();

$smartThumb->show_thumb();


/**
 * 智能输出缩略图
 * Class SmartThumb
 */
class SmartThumb
{
    private $rootPath = "";
    private $defaultPic = "/picture/nopic.jpg";
    private $pictureDir = "";
    private $thumbDir = "";
    private $size_rule = "";

    public function __construct()
    {
        $this->rootPath = dirname(__FILE__);
        $this->pictureDir = $this->rootPath . '/picture/';//原图路径
        $this->thumbDir = $this->rootPath . '/thumb/';//缩略图路径
        $this->size_rule = "100_100|200_200|300_300|400_400|500_500";//剪裁规则规则
    }

    /**
     * 显示缩略图
     */
    public function show_thumb()
    {
        //获取图片参数,参数名由apache review规则设置
        $url = $_GET['url'];
        //原地址
        $src = $this->pictureDir . preg_replace('/_(\d+)_(\d+)/', '', $url);
        //缩略图地址
        $filename = $this->thumbDir . $url;
        //检查原图是否存在
        if (!file_exists($src)) {
            $this->no_picture();
        }
        //解析目标缩略图分辨率参数
        if (!preg_match('/_(\d+)_(\d+)/', $url, $wh)) {
            $this->no_picture();
        }
        list(, $width, $height) = $wh;
        //检查图片分辨率规则
        $this->check_size_rule($width, $height);
        //创建缩略图
        $this->create_thumb($src, $width, $height, $filename, 'crop', '85');
    }

    /**
     * 检查图片分辨率规则
     * @param $width number 宽度
     * @param $height number 高度
     */
    private function check_size_rule($width, $height)
    {
        if (!in_array($width . '_' . $height, explode('|', $this->size_rule))) {
            $this->no_picture();
        }
    }

    /**
     * 创建缩略图
     * @param $src string 原图路径
     * @param $width number 目标宽度
     * @param $height number 目标高度
     * @param $filename string 目标路径
     * @param string $mode
     * @param string $quality 图片质量值
     */
    private function create_thumb($src, $width, $height, $filename, $mode = 'scale', $quality = '100')
    {
        try {
            $imageValue = getimagesize($src);
            $sourceWidth = $imageValue[0]; //原图宽
            $sourceHeight = $imageValue[1]; //原图高
            $thumbWidth = $width; //缩略图宽
            $thumbHeight = $height; //缩略图高
            $_x = 0;
            $_y = 0;
            $w = $sourceWidth;
            $h = $sourceHeight;
            if ($mode == 'scale') {
                if ($sourceWidth <= $thumbWidth && $sourceHeight <= $thumbHeight) {
                    $_x = floor(($thumbWidth - $sourceWidth) / 2);
                    $_y = floor(($thumbHeight - $sourceHeight) / 2);
                    $thumbWidth = $sourceWidth;
                    $thumbHeight = $sourceHeight;
                } else {
                    if ($thumbHeight * $sourceWidth > $thumbWidth * $sourceHeight) {
                        $thumbHeight = floor($sourceHeight * $width / $sourceWidth);
                        $_y = floor(($height - $thumbHeight) / 2);
                    } else {
                        $thumbWidth = floor($sourceWidth * $height / $sourceHeight);
                        $_x = floor(($width - $thumbWidth) / 2);
                    }
                }
            } else if ($mode == 'crop') {
                if ($sourceHeight < $thumbHeight) { //如果原图尺寸小于当前尺寸
                    $thumbWidth = floor($thumbWidth * $sourceHeight / $thumbHeight);
                    $thumbHeight = $sourceHeight;
                }
                if ($sourceWidth < $thumbWidth) {
                    $thumbHeight = floor($thumbHeight * $sourceWidth / $thumbWidth);
                    $thumbWidth = $sourceWidth;
                }

                $s1 = $sourceWidth / $sourceHeight; //原图比例
                $s2 = $width / $height; //新图比例
                if ($s1 == $s2) {

                } else if ($s1 > $s2) { //全高度
                    $y = 0;
                    $ax = floor($sourceWidth * ($thumbHeight / $sourceHeight));
                    $x = ($ax - $thumbWidth) / 2;
                    $w = $thumbWidth / ($thumbHeight / $sourceHeight);

                } else { //全宽度
                    $x = 0;
                    $ay = floor($sourceHeight * ($thumbWidth / $sourceWidth)); //模拟原图比例高度
                    $y = ($ay - $thumbHeight) / 2;
                    $h = $thumbHeight / ($thumbWidth / $sourceWidth);
                }

            }
            switch ($imageValue[2]) {
                case 2:
                    $source = imagecreatefromjpeg($src);
                    break;
                case 1:
                    $source = imagecreatefromgif($src);
                    break;
                case 3:
                    $source = imagecreatefrompng($src);
                    break;
                case 6:
                    $source = imagecreatefromwbmp($src);
                    break;
                default:
                    $this->no_picture();
                    return;
            }
            header("Content-type: image/jpeg");
            $thumb = imagecreatetruecolor($width, $height);
            imagefill($thumb, 0, 0, imagecolorallocate($thumb, 255, 255, 255));
            imagecopyresampled($thumb, $source, 0, 0, $x, $y, $width, $height, $w, $h);
            imagejpeg($thumb, null, $quality);
// if ($_SERVER['HTTP_REFERER'] || false !== stripos($_SERVER['HTTP_REFERER'], 'http://' . $_SERVER['SERVER_NAME'])) {
            imagejpeg($thumb, $filename, $quality);
// }
            imagedestroy($thumb);
            imagedestroy($source);
        } catch (Exception $ex) {
            $this->no_picture();
        }
    }

    /**
     * 显示默认图片
     */
    private function no_picture()
    {
        ob_start();
        header('Content-type:image/jpeg');
        readfile($this->rootPath . $this->defaultPic);
        ob_flush();
        flush();
        exit();
    }

}
